<!-- 百人(大逃杀) -->
<template>
  <el-dialog v-if="props.show" :model-value="props.show" :title="'【百人场】' + data.game_name" top="8vh" width="58%"
    @close="onHideDetails" :close-on-press-escape="false" :destroy-on-close="true" :close-on-click-modal="false">
    <div v-loading="indexStore.moduleLoading">
      <div class="dialogMaxHeight" :class="props.isDisableUser ? 'disableUser' : ''">
        <el-form ref="ruleFormRef" :model="data" :inline="true" :rules="rules" :scroll-to-error="true">
          <form-item title="游戏名称" value="game_name">
            <GameHeaderInfo :game_id="props.checkedItem.game_id" />
          </form-item>
          <form-item title="商户" :pass="true" value="agent_id" v-show="data.agent_id">
            <el-select v-model="data.agent_id" placeholder="请选择" filterable @change="chooseOperator">
              <el-option v-for="item in indexStore.agentArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
          </form-item>
          <form-item title="游戏水位" :pass="true" value="pool" v-show="data.agent_id && !indexStore.is_general_agent">
            <div class="flexWarp">
              <span class="margin5" v-for="(item, index) in data.serverPoolList" :key="index">
                <el-tag type="danger">{{ item.label }}</el-tag>：
                <el-input-number v-model="item.value" :min="-99999999999999999999" :max="99999999999999999999"
                  :precision="0" placeholder="游戏水位" clearable controls-position="right" />
              </span>
            </div>
          </form-item>
          <form-item title="房间最大人数" :pass="true" value="a_hundred_num" v-show="!indexStore.is_general_agent">
            <el-input-number v-model="data.a_hundred_num" :min="0" :max="99999999999999999999" :precision="0"
              placeholder="房间最大人数" clearable controls-position="right" />
          </form-item>
          <form-item title="抽水比例" :pass="true" value="a_hundred_pump">
            <el-input-number v-model="data.a_hundred_pump" :min="0" :max="100" :precision="4" placeholder="抽水比例"
              clearable controls-position="right" />%
          </form-item>
          <form-item title="押注金额" :pass="true" value="bet_range" :subtract="!props.isDisableUser"
            @addItem="addPressure">
            <div class="flex margin5" v-for="(item, index) in data.pressureList" :key="index">
              <el-input-number :min="0" :max="99999999999999999999" :precision="2" class="width150" v-model="item.num"
                placeholder="请输入押注大小" clearable controls-position="right" />
              <div v-show="!props.isDisableUser" class="reduce-btn reduce-btn_new marginL5"
                @click="reducePressure(index)">-</div>
            </div>
          </form-item>
          <form-item title="机器人注入" value="a_hundred_noperson">
            间隔判断时间:
            <el-input-number v-model="data.robotJoinTime" :min="0" :max="9999999999999999" :precision="0"
              class="width130 marginR15" placeholder="间隔判断时间" clearable :controls="false" />
            <div class="flexWrap margin5" v-for="(item, index) in data.robotJoinList" :key="index">
              {{ !index ? '左' : index == 1 ? '中间' : '右' }}端点数量下限:
              <el-input-number v-model="item.min" :min="0" :max="9999999999999999" :precision="4"
                class="width130 marginR15" placeholder="数量下限" clearable :controls="false" />
              {{ !index ? '左' : index == 1 ? '中间' : '右' }}端点数量上限:
              <el-input-number v-model="item.max" :min="0" :max="9999999999999999" :precision="4"
                class="width130 marginR15" placeholder="数量上限" clearable :controls="false" />
              权重:
              <el-input-number v-model="item.weight" :min="0" :max="999999999999999" :precision="0" class="width120"
                placeholder="权重" clearable :controls="false" />
            </div>
          </form-item>
          <form-item title="机器人数量控制" value="a_hundred_num" :subtract="!props.isDisableUser" @addItem="addRobotNum">
            <div class="flexWrap margin5" v-for="(item, index) in data.robotNumList" :key="index">
              时间起点:
              <el-input-number v-model="item.start" :min="0" :max="99999999999999999999" :precision="0"
                class="width110 marginR5" placeholder="时间起点" clearable :controls="false" />
              时间止点:
              <el-input-number v-model="item.end" :min="0" :max="99999999999999999999" :precision="0"
                class="width110 marginR5" placeholder="时间止点" clearable :controls="false" />
              机器人下限:
              <el-input-number v-model="item.min" :min="1" :max="99999999999999999999" :precision="0"
                class="width110 marginR5" placeholder="下限" clearable :controls="false" />
              机器人上限:
              <el-input-number v-model="item.max" :min="1" :max="99999999999999999999" :precision="0"
                class="width110 marginR5" placeholder="上限" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reduceRobotNum(index)">-</div>
            </div>
          </form-item>
          <form-item title="机器人计时押注" value="a_hundred_noperson" :subtract="!props.isDisableUser" @addItem="addTime">
            押注权重:
            <el-input-number v-model="data.betWeight" :min="0" :max="999999999999999" :precision="0"
              class="width150 marginR15" placeholder="押注权重" clearable :controls="false" />
            最大押注次数:
            <el-input-number v-model="data.betMaxNum" :min="0" :max="999999999999999" :precision="0"
              class="width150 marginR15" placeholder="最大押注次数" clearable :controls="false" />
            <div class="flexWrap margin5" v-for="(item, index) in data.robotTimeList" :key="index">
              {{ index + 1 }}段权重:
              <el-input-number v-model="item.weight" :min="0" :max="999999999999999" :precision="0"
                class="width150 marginR15" placeholder="权重" clearable :controls="false" />
              {{ index + 1 }}段时间下限:
              <el-input-number v-model="item.min" :min="1" :max="9999999999999999" :precision="0"
                class="width150 marginR15" placeholder="数量下限" clearable :controls="false" />
              {{ index + 1 }}段时间上限:
              <el-input-number v-model="item.max" :min="1" :max="9999999999999999" :precision="0" class="width150"
                placeholder="数量上限" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reduceTime(index)">-</div>
            </div>
          </form-item>
          <form-item title="下注时间段" :pass="true" value="a_hundred_operationcountdown">
            <el-input-number v-model="data.a_hundred_other_details.a_hundred_operationcountdown" :min="0" :max="100"
              :precision="0" class="width150" placeholder="下注时间段" clearable :controls="false" />
          </form-item>
          <form-item title="机器人离场控制" :pass="true" value="a_robot_leave">
            <div class="flexWrap margin5" v-for="(item, index) in data.robotLeaveList" :key="index">
              初始离开权重:
              <el-input-number v-model="item.start" :min="0" :max="99999999999999999999" :precision="0"
                class="width120 marginR10" placeholder="初始离开权重" clearable :controls="false" />
              每次判定后递增权重:
              <el-input-number v-model="item.end" :min="0" :max="99999999999999999999" :precision="0"
                class="width120 marginR10 marginT5" placeholder="递增权重" clearable :controls="false" />
              必走判定次数:
              <el-input-number v-model="item.min" :min="0" :max="99999999999999999999" :precision="0"
                class="width120 marginR10 marginT5" placeholder="必走判定次数" clearable :controls="false" />
              判定时间间隔:
              <el-input-number v-model="item.max" :min="0" :max="99999999999999999999" :precision="0"
                class="width120 marginT5" placeholder="判定时间间隔" clearable :controls="false" />
            </div>
          </form-item>
          <form-item title="水位配置" value="a_hundred_pool" :subtract="!props.isDisableUser" @addItem="addPool">
            <div class="flexWrap margin5" v-for="(item, index) in data.poolList" :key="index">
              水位下限:
              <el-input-number v-model="item.min" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginR5" placeholder="水位下限" clearable :controls="false" />
              水位上限:
              <el-input-number v-model="item.max" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginR5" placeholder="水位上限" clearable :controls="false" />
              权重:
              <el-input-number v-model="item.weight" :min="-1" :max="99999999999999999999" :precision="0"
                class="width120 marginR5" placeholder="权重" clearable :controls="false" />
              输上限额度:
              <el-input-number v-model="item.lose" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginT5" placeholder="输上限额度" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reducePool(index)">-</div>
            </div>
          </form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" v-show="!props.isDisableUser">
        <el-button type="info" @click="onHideDetails">取 消</el-button>
        <el-button type="primary" @click="gameSet(ruleFormRef)" v-loading="indexStore.moduleLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getHundredConfig, editHundredConfig, getPool, editPool } from '@/api/game'
import { BigWan, BigTimeWan } from '@/utils/math'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { throttle, selectToLabel } from '@/utils/index'
import type {
  MinMax,
  RobotHundred,
  Noperson,
  RobotPoolBattleRoyale
} from './gameType'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  isDisableUser: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

watch(
  () => [props.checkedItem, props.show],
  async (value) => {
    if (value[0]) {
      Object.assign(data, props.checkedItem)
    }
    if (value[1]) {
      chooseOperator(props.checkedItem.agent_id, props.checkedItem.game_id) // 获取运营商配置
    }
  }
)

const data = reactive({
  id: 0,
  game_id: 0,
  agent_id: 0,
  game_name: '',
  operated_id: indexStore.agentArray[0]?.value,
  a_hundred_num: 0, // 房间最大人数
  a_hundred_pump: 0, // 抽水比例
  a_hundred_other_details: {
    a_hundred_amount: '', // 下注额度
    a_hundred_operationcountdown: 0, // 下注时间段
    a_robot_hundred_join: '', // 机器人注入(间隔判定时间;左端点数量下限，数量上限，权重;中间数量下限，数量上限，权重;右端点数量下限，数量上限，权重)
    a_robot_hundred_carry: '', // 机器人入场携带(占比权重，下限，上限；……)
    a_robot_hundred_num: '', // 机器人数量控制（时间起点，时间终点，下限，上限；……）低于下限注入功能开启，高于上限注入功能关闭，离场功能始终开启，且离场1人所需时间<入场1人所需时间
    a_robot_leave: '', // 机器人离场控制(初始离开权重，每次判定后递增权重，必走判定次数，判定时间间隔)
    a_robot_hundred_stake_num: '', // 机器人人数押注(不足20人押注时间下限，不足20人押注时间上限，押注权重，判定间隔)
    a_robot_hundred_stake_time: '', // 机器人计时押注(押注权重,最大押注次数,1阶段权重，1阶段押注时间下限，1阶段押注时间上限，2阶段权重，2阶段押注时间下限，2阶段押注时间上限，……)计时押注以5秒为1个阶段60秒有12个阶段
    a_robot_hundred_stake_amount: '', // 机器人押注额度(百分比下限，百分比上限)
    a_hundred_pool: '', // 水位配置
  },
  pressureList: [{ num: 0 }], // 押注金额
  poolList: [] as RobotPoolBattleRoyale[], // 水位配置
  robotNumList: [] as RobotHundred[], // 机器人数量
  robotJoinTime: 0,// 机器人注入-间隔判断时间
  robotJoinList: [] as Noperson[], // 机器人注入
  robotCarryList: [] as Noperson[], // 机器人入场携带
  robotLeaveList: [] as RobotHundred[], // 机器人离场
  robotLimitList: [] as MinMax[], // 机器人押注额度
  betWeight: 0, // 机器人计时押注-押注权重
  betMaxNum: 0, // 机器人计时押注-最大押注次数
  robotTimeList: [] as Noperson[], // 机器人计时押注
  serverPoolList: [] as any[], // 服务器水位配置
})

// 选择运营商
const chooseOperator = async (id: number, game_id: number) => {
  indexStore.setModuleLoading(true)
  // 水位
  if (data.agent_id && !indexStore.is_general_agent) {
    data.serverPoolList = []
    let agent = await getPool({ agent_id: props.checkedItem.agent_id, game_id: props.checkedItem.game_id });
    let keyData = Object.keys(agent.data);
    keyData.forEach((key: string) => {
      data.serverPoolList.push({ label: selectToLabel(indexStore.serverNameList, key), value: BigWan(agent.data[key] ? agent.data[key] : 0), server: key })
    })
  }
  // 游戏详情
  let res = await getHundredConfig({ agent_id: id, game_id: game_id });
  Object.assign(data, res.data)
  nextTick(() => {
    indexStore.setModuleLoading(false)
  })
}

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<typeof data>>({
  a_hundred_num: [{ required: true, message: '请输入房间最大人数', trigger: 'blur' }],
  a_hundred_pump: [{ required: true, message: '请输入抽水比例', trigger: 'blur' }]
})
const gameSet = throttle(async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editHundredConfig(data)
      if (data.agent_id && !indexStore.is_general_agent) {
        // 按服务器修改水位
        let pools = [] as number[], server = [] as any[];
        data.serverPoolList.forEach((item: any) => {
          pools.push(BigTimeWan(item.value))
          server.push(item.server)
        })
        await editPool({
          agent_id: data.agent_id,
          game_id: data.game_id,
          pools: pools.join(','),
          server_ids: server.join(','),
        })
      }
      ElMessage.success('修改成功')
      emit('onHideDetails', true)
    }
  })
}, 3000)

// 新增押注倍数
const addPressure = () => {
  data.pressureList.push({ num: 0 })
}
// 减少押注倍数
const reducePressure = (index: number) => {
  if (!index && data.pressureList.length == 1) {
    return ElMessage.error('最少保留一个押注额度！')
  }
  data.pressureList.splice(index, 1)
}

// 机器人计时押注
const addTime = () => {
  data.robotTimeList.push({ min: 0, max: 1, weight: 0 })
}
const reduceTime = (index: number) => {
  data.robotTimeList.splice(index, 1)
}

// 机器人数量
const addRobotNum = () => {
  data.robotNumList.push({ start: 0, end: 1, min: 0, max: 1 })
}
const reduceRobotNum = (index: number) => {
  data.robotNumList.splice(index, 1)
}

// 水位配置
const addPool = () => {
  data.poolList.push({ min: 0, max: 1, weight: 0, lose: 0 })
}
const reducePool = (index: number) => {
  if (!index && data.poolList.length == 1) {
    return ElMessage.error('最少保留一个水位配置！')
  }
  data.poolList.splice(index, 1)
}

// 重置
const emit = defineEmits(['onHideDetails'])
const onHideDetails = () => {
  emit('onHideDetails', false)
}
</script>

<style scoped lang="scss">
.reduce-btn_new {
  position: absolute;
  right: 5px;
  bottom: -3px;
}
</style>